from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.database import get_db
from app.api.auth import get_current_user
from app.schemas.user import UserInDB

router = APIRouter()

# 创建工单
@router.post("/", response_model=schemas.TicketResponse, status_code=status.HTTP_201_CREATED)
def create_ticket(
    ticket: schemas.TicketCreate,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    # 验证关联的问题是否存在
    db_issue = crud.issue.get_issue(db, issue_id=ticket.issue_id)
    if not db_issue:
        raise HTTPException(status_code=404, detail="Issue not found")
    
    # 如果提供了案例ID，验证案例是否存在
    if ticket.case_id:
        db_case = crud.case.get_case(db, case_id=ticket.case_id)
        if not db_case:
            raise HTTPException(status_code=404, detail="Case not found")
    
    created_ticket = crud.ticket.create_ticket(db=db, ticket=ticket)
    return created_ticket

# 获取工单列表
@router.get("/", response_model=list[schemas.TicketResponse])
def read_tickets(
    skip: int = 0,
    limit: int = 100,
    issue_id: int = None,
    status: str = None,
    db: Session = Depends(get_db)
):
    tickets = crud.ticket.get_tickets(
        db, 
        skip=skip, 
        limit=limit, 
        issue_id=issue_id, 
        status=status
    )
    return tickets

# 获取工单详情
@router.get("/{ticket_id}", response_model=schemas.TicketResponse)
def read_ticket(ticket_id: int, db: Session = Depends(get_db)):
    db_ticket = crud.ticket.get_ticket(db, ticket_id=ticket_id)
    if db_ticket is None:
        raise HTTPException(status_code=404, detail="Ticket not found")
    return db_ticket

# 更新工单
@router.put("/{ticket_id}", response_model=schemas.TicketResponse)
def update_ticket(
    ticket_id: int,
    ticket: schemas.TicketUpdate,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    db_ticket = crud.ticket.get_ticket(db, ticket_id=ticket_id)
    if db_ticket is None:
        raise HTTPException(status_code=404, detail="Ticket not found")
    
    # 如果提供了案例ID，验证案例是否存在
    if ticket.case_id:
        db_case = crud.case.get_case(db, case_id=ticket.case_id)
        if not db_case:
            raise HTTPException(status_code=404, detail="Case not found")
    
    updated_ticket = crud.ticket.update_ticket(db, ticket_id=ticket_id, ticket=ticket)
    return updated_ticket

# 删除工单
@router.delete("/{ticket_id}", response_model=schemas.TicketResponse)
def delete_ticket(
    ticket_id: int,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    db_ticket = crud.ticket.get_ticket(db, ticket_id=ticket_id)
    if db_ticket is None:
        raise HTTPException(status_code=404, detail="Ticket not found")
    
    deleted_ticket = crud.ticket.delete_ticket(db, ticket_id=ticket_id)
    return deleted_ticket